package com.tanhua.dubbo.server.api.mongo;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Video video) {

        video.setId(ObjectId.get());

        video.setCreated(System.currentTimeMillis());

        mongoTemplate.save(video);
    }

    @Override
    public PageResult findAll(Integer page, Integer pageSize) {

        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));

        Query query = new Query().with(pageable);

        List<Video> videos = this.mongoTemplate.find(query, Video.class);

        Long counts = this.mongoTemplate.count(query, Video.class);

        return new PageResult(page,pageSize, counts.intValue(), videos);
    }

    @Override
    public void followUser(FollowUser followUser) {
        followUser.setId(ObjectId.get());
        followUser.setCreated(System.currentTimeMillis());
        this.mongoTemplate.save(followUser);
    }

    @Override
    public void disFollowUser(Long userId, Long followUserId) {
        Query query = Query.query(Criteria.where("userId")
                .is(userId)
                .and("followUserId")
                .is(followUserId));
        this.mongoTemplate.remove(query, FollowUser.class);
    }
}
